<template>
  <el-dropdown v-if="dropdown">
    <el-button link type='primary'>
      排序<el-icon class='el-icon--right'><arrow-down /></el-icon>
    </el-button>
    <template #dropdown>
      <div class='p-2 flex flex-col gap-2'>
        <div v-for="(d, i) in value" :key="i" class='flex justify-between items-center gap-2'>
          {{d.label}}
          <div class='flex flex-col gap-[1px]'>
            <el-icon :class="[sort.field === d.value && sort.order === 'asc' ? 'text-blue-600' : 'text-gray-400 hover:text-gray-600', 'cursor-pointer h-2']" size="16"
              @click="handleSort(d.value, 'asc')">
              <CaretTop />
            </el-icon>
            <el-icon :class="[sort.field === d.value && sort.order === 'desc' ? 'text-blue-600' : 'text-gray-400 hover:text-gray-600', 'cursor-pointer h-2']" size="16"
              @click="handleSort(d.value, 'desc')">
              <CaretBottom />
            </el-icon>
          </div>
        </div>
      </div>
    </template>
  </el-dropdown>
  <div v-else class='flex flex-col gap-2'>
    <div v-for="(d, i) in value" :key="i" class='flex items-center gap-1'>
      {{d.label}}
      <div class='flex flex-col'>
        <el-icon :class="[sort.field === d.value && sort.order === 'asc' ? 'text-blue-600' : 'text-gray-400 hover:text-gray-600', 'cursor-pointer h-2']" size="16"
          @click="handleSort(d.value, 'asc')">
          <CaretTop />
        </el-icon>
        <el-icon :class="[sort.field === d.value && sort.order === 'desc' ? 'text-blue-600' : 'text-gray-400 hover:text-gray-600', 'cursor-pointer h-2']" size="16"
          @click="handleSort(d.value, 'desc')">
          <CaretBottom />
        </el-icon>
      </div>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  modelValue: { type: Object, default: () => ({}) },
  value: { type: Array, default: () => ([]) },
  tableRef: { type: Object, default: () => ({}) },
  dropdown: Boolean,
})
const emit = defineEmits(['update:modelValue', 'change'])
const sort = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})

const handleSort = (name, s) => {
  sort.value.field = name
  sort.value.order = sort.value.field === name && sort.value.order === s ? '' : s
  const {tableRef} = props
  if(!tableRef?.value) return 
  tableRef?.value?.$table.clearSort()
  const {field, order: rule} = sort.value
  tableRef?.value.setFormField('sort', rule ? {field, rule} : {})
  tableRef?.value.query()
}
</script>